package monitor

import (
	"fmt"
    "time"
    "net"
    "os"
    "encoding/hex"
)

var checkConnect = []byte("check connect")

type Cconn struct {
	conn 		net.Conn
	ch 			chan []byte
	chSyn 		chan struct{}
	chStop 		chan struct{}
	established bool
	lf *DataFile
}



func (m *Monitor) recv(syn chan struct{}) {
	c := &m.c
	var buf [1460]byte
    for m.exitflag != true {
		c.conn.SetReadDeadline(time.Now().Add(6 * time.Second))
		n, err := c.conn.Read(buf[0:])
		if err != nil {
			if err.Error() == "EOF" {
	    		m.logf.WriteLogln("cmd recv EOF")
					break
	    	}else {
	    		IdbgCmd(2, "cmd rec time out")
				m.c.ch <- checkConnect	    	
				continue
			}
    	}
	    IdbgRecvHex(3, buf[0:n])
	    IdbgCmd(2, "cmd rec", n, "bytes")
	    m.pg.cmdwcnt = cmdWcntMax
	    TsParse(buf[0:n], m.region.CmdPid, &m.pg)
    }
    syn<- struct{}{}
}

func (m *Monitor) sendv(syn chan struct{}) {
	c := &m.c
	hearttick := time.Tick(1000 * time.Millisecond)
    for m.exitflag != true {
        select {
        case _, ok := <-syn:
            if !ok {
            	return
            }
        case msg, ok := <-c.ch:
        	if ok {
				_, err := c.conn.Write(msg)
	        	if err != nil {
					return
	        	}
	        	IdbgSend(2, "cmd send", msg)
            }
        case <-hearttick: 
			//m.logf.WriteLogln("run")
        }
    }
    syn<- struct{}{}
}


func pack_loadbytes(cmdpid uint16, logicStr string) []byte{
	var load= []byte{0x02, 0x00, 0x0e, 0x51, 0x01 ,0x08, 0x01, 0x01, 0x09, 0x15, 0x08, 0x05, 0x50, 0x10, 0x01, 0x1a, 0x23}
	logicBytes, _ := hex.DecodeString(logicStr)
	copy(load[3:9], logicBytes)
	load[15] = byte(cmdpid >> 8)
	load[16] = byte(cmdpid&0xff)
	return load
}

func (pg *PgInfo) ReInit() {
	pg.CmdStop()
	pg.lastPgid	= 0
	pg.playwcnt = 0
	pg.cmdwcnt = 0
}

func (pg *PgInfo) CmdStop() {
	pg.cmdLv = 0
	pg.logicAddr = [6]byte{0,0,0,0,0,0}
	pg.swSta = pgCmdStop
	pg.emFlag = 0
	pg.pgId	= 0
}


func (m *Monitor) RunCmd(remoteIp string, ch chan []byte) {
	c := &m.c
	addr, err := net.ResolveTCPAddr("tcp4", remoteIp)
	if err != nil {
        fmt.Println("ResolveTCPAddr error:", err.Error())
        os.Exit(1)
    }
    c.ch = ch
    c.chSyn = make(chan struct{})
    c.chStop = make(chan struct{})
    for {
        c.conn, err = net.DialTCP("tcp", nil, addr)
        if err == nil {
            defer c.conn.Close()
		    go m.sendv(c.chSyn)

		    /*send online bytes*/
		    m.pg.ReInit()
		    loadBytes := pack_loadbytes(m.region.CmdPid, m.region.Logicid)
		    c.ch <- loadBytes
		    
			c.established = true
			m.pg.cmdwcnt = 180
			m.exitflag = false
		    m.logf.WriteLogln("cmd 网络连接成功", addr)
            m.recv(c.chSyn)
            <- c.chStop
            <- c.chStop
            m.logf.WriteLogln("cmd 网络断开")
            c.established = false
            
        }
        time.Sleep(2 * time.Second)
    }
}







